package base.thread_demo.demo08_01;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * sleep,wait等方法等待时对锁的释放与否演示
 * sleep() 不释放锁进入阻塞
 * wait()释放锁进入阻塞
 */
public class ReleaseLock {
    private static final Logger log = LoggerFactory.getLogger(ReleaseLock.class);

    // final从Java语法上就规定不可以引用指向改变，保证了监控对象是同一个对象。
    private static final Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            synchronized (lock){
                log.info("{} 获得了锁,开始进入睡眠...", Thread.currentThread().getName());
                try {
//                    Thread.sleep(5000); // 不释放锁进入阻塞
                    lock.wait(); // 释放锁进入阻塞
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("{} 继续运行", Thread.currentThread().getName());
            }
        },"t1").start();

        Thread.sleep(1000);//尽可能让t1线程先拿到锁执行.

        synchronized (lock){
            log.info("{} 获得了锁", Thread.currentThread().getName());
//            lock.notify();//唤醒t1,否则程序僵死
        }

    }


}
